<template>
  <div class="info">
    <div class="card">
      <h3>修改用户信息</h3>
      <div class="form">
        <el-form ref="ruleFormRef" label-position="right" label-width="100px" :model="userInfo" :rules="rules">
          <el-form-item label="登录名称" prop="username">
            <el-input v-model="userInfo.username" />
          </el-form-item>
          <el-form-item label="用户昵称" prop="nickname">
            <el-input v-model="userInfo.nickname" />
          </el-form-item>
          <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="userInfo.email" />
          </el-form-item>
        </el-form>
      </div>
      <div class="btn-area">
        <el-button type="primary" @click="submit">提交修改</el-button>
        <el-button @click="reset">重置</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { getUserInfo, changeUserInfo } from '@/api/myCenter/index.js'
import { ElMessage } from 'element-plus'
import { ref, reactive } from 'vue'

const userInfoBase = {
  username: '',
  nickname: '',
  email: ''
}
const userInfo = reactive({ ...userInfoBase })
const ruleFormRef = ref()

const validatePass = (rule, value, callback) => {
  if (value !== '') {
    const flag = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)
    flag ? callback() : callback(new Error('邮箱格式错误'))
  }
  callback()
}

const rules = reactive({
  username: [
    { required: true, message: '不能为空', trigger: 'blur' },
    { min: 3, max: 10, message: 'Length should be 3 to 10', trigger: 'blur' },
  ],
  nickname: [{ required: true, message: '不能为空', trigger: 'blur' }],
  email: [{ validator: validatePass, trigger: 'blur' },]
})

getUserInfo().then(el => {
  if (el.code === 0) {
    ({ username: userInfo.username, nickname: userInfo.nickname, email: userInfo.email } = el.data)
  }
})

function submit() {
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      changeUserInfo(userInfo).then(el => {
        if (el.code === 0) {
          ElMessage({
            message: el.message,
            type: 'success',
            duration: 3 * 1000
          })
        }
      })
    }
  })
}

function reset() {
  Object.assign(userInfo, { ...userInfoBase });
}


</script>

<style lang="scss" scoped></style>